<template>
  <div class="alert-history">
    <!-- 告警概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>今日告警数</span>
              <el-tag type="danger">{{ alertStats.todayCount }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="alertStats.todayTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(alertStats.todayTrend) }}%
                <el-icon>
                  <component :is="alertStats.todayTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>待处理告警</span>
              <el-tag type="warning">{{ alertStats.pendingCount }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="alertStats.pendingTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(alertStats.pendingTrend) }}%
                <el-icon>
                  <component :is="alertStats.pendingTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>平均响应时间</span>
              <el-tag type="info">{{ alertStats.avgResponseTime }}分钟</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="alertStats.responseTimeTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(alertStats.responseTimeTrend) }}%
                <el-icon>
                  <component :is="alertStats.responseTimeTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <template #header>
            <div class="card-header">
              <span>告警解决率</span>
              <el-tag type="success">{{ alertStats.resolutionRate }}%</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="alertStats.resolutionTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(alertStats.resolutionTrend) }}%
                <el-icon>
                  <component :is="alertStats.resolutionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 告警趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>告警趋势分析</span>
              <el-radio-group v-model="trendTimeRange" size="small">
                <el-radio-button label="hour">1小时</el-radio-button>
                <el-radio-button label="day">24小时</el-radio-button>
                <el-radio-button label="week">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="trendChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>告警类型分布</span>
              <el-radio-group v-model="distributionTimeRange" size="small">
                <el-radio-button label="day">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="distributionChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 告警列表 -->
    <el-card shadow="hover" class="alert-list-card">
      <template #header>
        <div class="card-header">
          <span>告警历史记录</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">导出</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="告警名称">
            <el-input v-model="searchForm.name" placeholder="请输入告警名称" clearable />
          </el-form-item>
          <el-form-item label="告警类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="系统告警" value="system" />
              <el-option label="业务告警" value="business" />
              <el-option label="性能告警" value="performance" />
              <el-option label="安全告警" value="security" />
            </el-select>
          </el-form-item>
          <el-form-item label="告警级别">
            <el-select v-model="searchForm.level" placeholder="请选择级别" clearable>
              <el-option label="严重" value="严重" />
              <el-option label="高" value="高" />
              <el-option label="中" value="中" />
              <el-option label="低" value="低" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已解决" value="resolved" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 告警列表 -->
      <el-table :data="alertList" border v-loading="loading">
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="告警名称" min-width="150" />
        <el-table-column prop="type" label="告警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeTag(row.type)">{{ getAlertTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="告警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertLevelTag(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="告警内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="告警时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="处理人" width="120" />
        <el-table-column prop="handleTime" label="处理时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="primary"
              link
              @click="handleProcess(row)"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 告警详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="告警详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="告警名称">{{ currentAlert.name }}</el-descriptions-item>
        <el-descriptions-item label="告警类型">
          <el-tag :type="getAlertTypeTag(currentAlert.type)">
            {{ getAlertTypeLabel(currentAlert.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="告警级别">
          <el-tag :type="getAlertLevelTag(currentAlert.level)">{{ currentAlert.level }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="告警状态">
          <el-tag :type="getStatusTag(currentAlert.status)">
            {{ getStatusLabel(currentAlert.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="告警时间">{{ currentAlert.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理人">{{ currentAlert.handler || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ currentAlert.handleTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="告警内容" :span="2">{{ currentAlert.content }}</el-descriptions-item>
        <el-descriptions-item label="告警详情" :span="2">
          <pre class="alert-detail">{{ currentAlert.detail }}</pre>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>处理记录</el-divider>

      <el-timeline>
        <el-timeline-item
          v-for="record in processRecords"
          :key="record.id"
          :type="getTimelineItemType(record.status)"
          :timestamp="record.createTime"
        >
          <h4>{{ getStatusLabel(record.status) }}</h4>
          <p>处理人：{{ record.handler }}</p>
          <p>处理说明：{{ record.comment }}</p>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 处理告警对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理告警"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="处理中" value="processing" />
            <el-option label="已解决" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理说明" prop="comment">
          <el-input
            v-model="processForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入处理说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleProcessSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getAlertHistoryList,
  getAlertHistoryStats,
  getAlertHistoryTrend,
  getAlertHistoryDistribution,
  getAlertHistoryDetail,
  processAlert,
  exportAlertHistory
} from '@/api/message'

// 告警统计数据
const alertStats = reactive({
  todayCount: 0,
  todayTrend: 0,
  pendingCount: 0,
  pendingTrend: 0,
  avgResponseTime: 0,
  responseTimeTrend: 0,
  resolutionRate: 0,
  resolutionTrend: 0
})

// 图表相关
const trendChartRef = ref(null)
const distributionChartRef = ref(null)
let trendChart = null
let distributionChart = null
const trendTimeRange = ref('hour')
const distributionTimeRange = ref('day')

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  level: '',
  status: '',
  timeRange: []
})

// 列表数据
const alertList = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const currentAlert = reactive({})
const processRecords = ref([])

// 处理对话框
const processDialogVisible = ref(false)
const processFormRef = ref(null)
const processForm = reactive({
  id: '',
  status: '',
  comment: ''
})

// 处理表单验证规则
const processRules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  comment: [{ required: true, message: '请输入处理说明', trigger: 'blur' }]
}

// 加载告警统计数据
const loadAlertStats = async () => {
  try {
    const res = await getAlertHistoryStats()
    Object.assign(alertStats, res.data)
  } catch (error) {
    ElMessage.error('加载告警统计数据失败')
  }
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  trendChart = echarts.init(trendChartRef.value)
  updateTrendChart()
}

// 更新趋势图表
const updateTrendChart = async () => {
  if (!trendChart) return
  try {
    const res = await getAlertHistoryTrend({ timeRange: trendTimeRange.value })
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['告警数量', '已处理数量']
      },
      xAxis: {
        type: 'category',
        data: res.data.timestamps
      },
      yAxis: {
        type: 'value',
        name: '数量'
      },
      series: [
        {
          name: '告警数量',
          type: 'line',
          data: res.data.alertCounts,
          smooth: true
        },
        {
          name: '已处理数量',
          type: 'line',
          data: res.data.processedCounts,
          smooth: true
        }
      ]
    }
    trendChart.setOption(option)
  } catch (error) {
    ElMessage.error('加载趋势数据失败')
  }
}

// 初始化分布图表
const initDistributionChart = () => {
  if (!distributionChartRef.value) return
  distributionChart = echarts.init(distributionChartRef.value)
  updateDistributionChart()
}

// 更新分布图表
const updateDistributionChart = async () => {
  if (!distributionChart) return
  try {
    const res = await getAlertHistoryDistribution({ timeRange: distributionTimeRange.value })
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: res.data.distribution,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    distributionChart.setOption(option)
  } catch (error) {
    ElMessage.error('加载分布数据失败')
  }
}

// 加载告警列表
const loadAlertList = async () => {
  try {
    loading.value = true
    const [startTime, endTime] = searchForm.timeRange || []
    const res = await getAlertHistoryList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm,
      startTime,
      endTime
    })
    alertList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('加载告警列表失败')
  } finally {
    loading.value = false
  }
}

// 查看告警详情
const handleViewDetail = async (row) => {
  try {
    const res = await getAlertHistoryDetail(row.id)
    Object.assign(currentAlert, res.data.alert)
    processRecords.value = res.data.records
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载告警详情失败')
  }
}

// 处理告警
const handleProcess = (row) => {
  processForm.id = row.id
  processForm.status = ''
  processForm.comment = ''
  processDialogVisible.value = true
}

// 提交处理
const handleProcessSubmit = async () => {
  if (!processFormRef.value) return
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await processAlert(processForm)
        ElMessage.success('处理告警成功')
        processDialogVisible.value = false
        loadAlertList()
        loadAlertStats()
      } catch (error) {
        ElMessage.error('处理告警失败')
      }
    }
  })
}

// 导出告警历史
const handleExport = async () => {
  try {
    const [startTime, endTime] = searchForm.timeRange || []
    await exportAlertHistory({
      ...searchForm,
      startTime,
      endTime
    })
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  loadAlertList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'timeRange' ? [] : ''
  })
  handleSearch()
}

// 刷新
const handleRefresh = () => {
  loadAlertStats()
  loadAlertList()
  updateTrendChart()
  updateDistributionChart()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadAlertList()
}

const handleCurrentChange = (val) => {
  page.value = val
  loadAlertList()
}

// 工具方法
const getAlertTypeLabel = (type) => {
  const map = {
    system: '系统告警',
    business: '业务告警',
    performance: '性能告警',
    security: '安全告警'
  }
  return map[type] || type
}

const getAlertTypeTag = (type) => {
  const map = {
    system: 'danger',
    business: 'warning',
    performance: 'info',
    security: 'error'
  }
  return map[type] || 'info'
}

const getAlertLevelTag = (level) => {
  const map = {
    严重: 'danger',
    高: 'error',
    中: 'warning',
    低: 'info'
  }
  return map[level] || 'info'
}

const getStatusLabel = (status) => {
  const map = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    closed: '已关闭'
  }
  return map[status] || status
}

const getStatusTag = (status) => {
  const map = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success',
    closed: 'info'
  }
  return map[status] || 'info'
}

const getTimelineItemType = (status) => {
  const map = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success',
    closed: 'info'
  }
  return map[status] || 'info'
}

// 监听时间范围变化
watch(trendTimeRange, () => {
  updateTrendChart()
})

watch(distributionTimeRange, () => {
  updateDistributionChart()
})

// 监听窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  distributionChart?.resize()
}

// 初始化
onMounted(() => {
  loadAlertStats()
  loadAlertList()
  initTrendChart()
  initDistributionChart()
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  distributionChart?.dispose()
})
</script>

<style lang="scss" scoped>
.alert-history {
  padding: 20px;
  .overview-row {
    margin-bottom: 20px;
    .overview-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .card-content {
        .trend {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 10px;
          .up {
            color: #67c23a;
          }
          .down {
            color: #f56c6c;
          }
        }
      }
    }
  }
  .chart-row {
    margin-bottom: 20px;
    .chart-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .chart-container {
        height: 300px;
      }
    }
  }
  .alert-list-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    .search-bar {
      margin-bottom: 20px;
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  .alert-detail {
    margin: 0;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-family: monospace;
    white-space: pre-wrap;
    word-break: break-all;
  }
}
</style> 